package com.da.web.sys_menu.entity;

import com.da.web.sys_login.entity.RouterVo;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @author da
 * @time 2023/12/2 上午 9:48
 * 生成菜单树的工具类
 */
public class MakeTree {

    public static List<SysMenu> makeMenuTree(List<SysMenu> menuList, Long pid) {
        //根容器
        List<SysMenu> root = new ArrayList<>();
        Optional.ofNullable(menuList).orElse(new ArrayList<>())
                .stream()
                .filter(i -> i != null && Objects.equals(i.getParentId(), pid))
                .forEach(dom -> {
                    SysMenu menu = new SysMenu();
                    BeanUtils.copyProperties(dom, menu);
                    //查询下级菜单
                    List<SysMenu> children = makeMenuTree(menuList, dom.getMenuId());
                    menu.setChildren(children);
                    root.add(menu);
                });
        return root;
    }

    //组装路由数据
    public static List<RouterVo> makeRouter(List<SysMenu> menuList, Long pid) {
        List<RouterVo> root = new ArrayList<>();
        //组装数据格式
        Optional.ofNullable(menuList).orElse(new ArrayList<>())
                .stream()
                .filter(item -> item != null && Objects.equals(item.getParentId(), pid))
                .forEach(item -> {
                    RouterVo router = new RouterVo();
                    router.setName(item.getName());
                    router.setPath(item.getPath());
                    if (item.getParentId() == 0L) {
                        //目录
                        router.setComponent("Layout");
                    } else {
                        router.setComponent(item.getUrl());
                    }
                    router.setMeta(router.new Meta(
                            item.getTitle(),
                            item.getIcon(),
                            item.getCode().split(","),
                            false
                    ));
                    //查询下级
                    List<RouterVo> children = makeRouter(menuList, item.getMenuId());
                    router.setChildren(children);
                    root.add(router);
                });
        return root;
    }


}
